package com.rbac.service.impl;

import com.rbac.dto.RoleQueryDTO;
import com.rbac.entity.SysRole;
import com.rbac.mapper.RoleMapper;
import com.rbac.service.RoleService;
import com.rbac.vo.RoleVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
	
	@Autowired
	private RoleMapper roleMapper;
	
	@Override
	public SysRole getRoleByRoleCode(String roleCode) {
		return roleMapper.selectByRoleCode(roleCode);
	}
	
	@Override
	public SysRole getRoleById(Long id) {
		return roleMapper.selectById(id);
	}
	
	@Override
	public PageInfo<RoleVO> getRoleList(RoleQueryDTO queryDTO) {
		PageHelper.startPage(queryDTO.getPageNum(), queryDTO.getPageSize());
		
		List<RoleVO> roleList = roleMapper.selectRoleList(queryDTO);
		
		// 为每个角色设置权限名称
		for (RoleVO roleVO : roleList) {
			List<String> permissionNames = roleMapper.selectPermissionNamesByRoleId(roleVO.getId());
			roleVO.setPermissionNames(permissionNames);
		}
		
		return new PageInfo<>(roleList);
	}
	
	@Override
	@Transactional
	public boolean addRole(SysRole role) {
		// 检查角色编码是否已存在
		SysRole existRole = roleMapper.selectByRoleCode(role.getRoleCode());
		if (existRole != null) {
			return false;
		}
		
		role.setStatus(1); // 默认启用
		role.setSortOrder(0); // 默认排序
		role.setCreateTime(LocalDateTime.now());
		role.setUpdateTime(LocalDateTime.now());
		
		return roleMapper.insert(role) > 0;
	}
	
	@Override
	@Transactional
	public boolean updateRole(SysRole role) {
		role.setUpdateTime(LocalDateTime.now());
		return roleMapper.update(role) > 0;
	}
	
	@Override
	@Transactional
	public boolean deleteRole(Long id) {
		return roleMapper.deleteById(id) > 0;
	}
	
	@Override
	@Transactional
	public boolean updateRoleStatus(Long id, Integer status) {
		SysRole role = new SysRole();
		role.setId(id);
		role.setStatus(status);
		role.setUpdateTime(LocalDateTime.now());
		return roleMapper.update(role) > 0;
	}
	
	@Override
	public List<Long> getPermissionIdsByRoleId(Long roleId) {
		List<Long> ids = roleMapper.selectPermissionIdsByRoleId(roleId);
		return ids == null ? Collections.emptyList() : ids;
	}
	
	@Override
	@Transactional
	public boolean assignPermissions(Long roleId, List<Long> permissionIds) {
		// 先清空旧的关联
		roleMapper.deleteRolePermissionsByRoleId(roleId);
		// 如果新的权限为空，视为清空权限，直接返回true
		if (permissionIds == null || permissionIds.isEmpty()) {
			return true;
		}
		// 批量插入
		return roleMapper.insertRolePermissions(roleId, permissionIds) > 0;
	}
} 